package com.linkoog.devtools.archive.filesystem.tar;

import com.linkoog.devtools.archive.filesystem.ArchiveHandlerBase;
import com.linkoog.devtools.archive.filesystem.ArchiveFile;
import com.linkoog.devtools.archive.util.ArchiveUtils;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

/**
 */
public class TarFile implements ArchiveFile {

    protected final File _file;

    protected FileInputStream _fileInputStream;

    protected Map<String, ArchiveEntry> entries;

    public TarFile(File file) {
        _file = file;
    }

    @Override
    public Map<String, ArchiveHandlerBase.EntryInfo> createEntriesInfoMap() throws IOException{
        try (ArchiveInputStream inputStream =  getInputStream()){
            return ArchiveUtils.buildEntryMap(calculateEntries());
        }
    }

    @Override
    public byte[] getEntryBytes(String relativePath) throws IOException{
        ArchiveEntry item = calculateEntries().get(relativePath);
        try (ArchiveInputStream inputStream =  getInputStream()){
            return ArchiveUtils.getEntryBytes(inputStream, item);
        }
    }

    @Override
    public ArchiveInputStream getInputStream() throws IOException{
        _fileInputStream = new FileInputStream(_file);
        return new TarArchiveInputStream(_fileInputStream);
    }

    @Override
    public void close() throws IOException{
        if (_fileInputStream != null)  _fileInputStream.close();
    }

    public Map<String, ArchiveEntry> calculateEntries() throws IOException{
        if (entries == null) {
            try (ArchiveInputStream inputStream =  getInputStream()){
                entries = ArchiveUtils.calculateEntries(inputStream);
                return entries;
            }
        } else {
            return entries;
        }
    }

}